package com.algorithm.example.queue.deque;

import java.util.Iterator;

/**
 * <p>
 * 链表双端队列
 * </p>
 *
 * @author lzt
 * @version 1.0
 * @since 2024/1/27 12:08
 */
public class LinkedListDeque<E> implements Deque<E>, Iterable<E> {

    private Node<E> head = new Node<>(null, null, null);

    private Node<E> tail = head;

    private int size;

    int capacity;

    private static class Node<E> {
        private Node<E> prev;
        private E value;
        private Node<E> next;

        public Node(Node prev, E value, Node<E> next) {
            this.prev = prev;
            this.value = value;
            this.next = next;
        }
    }

    public LinkedListDeque(int capacity) {
        this.capacity = capacity;
        head.next = tail;
        tail.prev = head;
    }

    @Override
    public boolean offerFirst(E e) {
        if (isFull()) {
            return false;
        }
        Node<E> next = head.next;
        Node<E> eNode = new Node<>(head, e, next);
        head.next = eNode;
        next.prev = eNode;
        return true;
    }

    @Override
    public boolean offerLast(E e) {
        if(isFull()) {
            return false;
        }
        Node<E> prev = tail.prev;
        Node<E> eNode = new Node<>(prev, e, tail);
        prev.next = eNode;
        tail.prev = eNode;
        return true;
    }

    @Override
    public E pollFirst() {
        if(isEmpty()) {
            return null;
        }
        Node<E> next = head.next;
        E value = next.value;
        head.next = next.next;
        next.prev = head;
        return value;
    }

    @Override
    public E pollLast() {
        if(isEmpty()) {
            return null;
        }
        Node<E> prev = tail.prev;
        E value = prev.value;
        tail.prev = prev.prev;
        prev.prev.next = tail;
        return value;
    }

    @Override
    public E peekFirst() {
        if(isEmpty()) {
            return null;
        }
        return head.next.value;
    }

    @Override
    public E peekLast() {
        if(isEmpty()) {
            return null;
        }
        return tail.prev.value;
    }

    @Override
    public boolean isEmpty() {
        return head.next == null;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
